package com.io;

import java.io.*;

public class FileIoTest {
    public static void main(String[] args) {
//        String sourcePath = "D:\\FileIo\\source.txt";
//        String targetPath = "D:\\FileIo\\target.txt";
//
//        try {
//            copyUsingStreams(sourcePath, targetPath);
//            System.out.println("文件拷贝成功！");
//        } catch (IOException e) {
//            System.out.println("文件拷贝失败: " + e.getMessage());
//        }



//        try (PrintWriter writer = new PrintWriter("D:\\FileIo\\printw.txt")) {
//            writer.println("Hello, PrintWriter!");
//            writer.printf("当前时间: %tF %tT%n", System.currentTimeMillis(), System.currentTimeMillis());
//            writer.print("PI 的值: ");
//            writer.println(Math.PI);
//
//            // 检查是否发生错误
//            if (writer.checkError()) {
//                System.err.println("写入文件时发生错误！");
//            }
//            System.out.println("printwriter over");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }

        printWriterOut();


    }




    private static void copyUsingStreams(String source, String target) throws IOException {
        try (InputStream in = new FileInputStream(source);
             OutputStream out = new FileOutputStream(target)) {

            byte[] buffer = new byte[8192]; // 8KB 缓冲区
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }

    //指定字符编码
    public static void printWriterOut() {
        try(PrintWriter writer = new PrintWriter(new OutputStreamWriter(
                new FileOutputStream("D:\\FileIo\\utf8.txt"),
                "UTF-8"))) {
            writer.println("UTF-8 编码文本: 你好，世界！");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
}
